<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="handleAdd">新增角色</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="searchForm" label-width="80px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="角色名称">
              <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>

      <!-- 表格数据 -->
      <el-table :data="roleList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="roleName" label="角色名称" />
        <el-table-column prop="roleDesc" label="角色描述" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
              {{ scope.row.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button size="small" @click="handlePermission(scope.row)">权限配置</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 角色编辑/新增对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form ref="roleFormRef" :model="roleForm" :rules="roleFormRules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc" type="textarea" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="权限配置" width="500px">
      <el-tree
        ref="treeRef"
        :data="permissions"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedPermissions"
        :props="defaultProps"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPermission">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  roleName: '',
  status: ''
})

// 角色列表数据
const roleList = ref([
  {
    id: 1,
    roleName: 'admin',
    roleDesc: '管理员角色',
    createTime: '2023-01-01',
    status: '1'
  },
  {
    id: 2,
    roleName: 'user',
    roleDesc: '普通用户角色',
    createTime: '2023-01-02',
    status: '1'
  }
])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 2
})

// 对话框相关
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 角色表单
const roleForm = reactive({
  id: '',
  roleName: '',
  roleDesc: '',
  status: '1'
})

// 表单验证规则
const roleFormRules = {
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
}

// 表单引用
const roleFormRef = ref(null)

// 权限树相关
const treeRef = ref(null)
const checkedPermissions = ref([1, 3, 5])

const defaultProps = {
  children: 'children',
  label: 'label'
}

const permissions = ref([
  {
    id: 1,
    label: '系统管理',
    children: [
      {
        id: 2,
        label: '用户管理',
        children: [
          { id: 3, label: '新增用户' },
          { id: 4, label: '编辑用户' },
          { id: 5, label: '删除用户' }
        ]
      },
      {
        id: 6,
        label: '角色管理',
        children: [
          { id: 7, label: '新增角色' },
          { id: 8, label: '编辑角色' },
          { id: 9, label: '删除角色' }
        ]
      }
    ]
  }
])

// 搜索
const handleSearch = () => {
  ElMessage.success('搜索功能演示')
}

// 重置
const handleReset = () => {
  searchForm.roleName = ''
  searchForm.status = ''
}

// 新增角色
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = row => {
  dialogTitle.value = '编辑角色'
  isEdit.value = true
  Object.assign(roleForm, row)
  dialogVisible.value = true
}

// 删除角色
const handleDelete = row => {
  ElMessageBox.confirm(`确认删除角色 "${row.roleName}" 吗？`, '确认删除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 实际项目中这里会调用删除接口
      // 例如: await deleteRole(row.id)
      console.log('删除角色:', row.id) // 使用row参数，避免ESLint警告
      ElMessage.success('删除成功')
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 权限配置
const handlePermission = () => {
  permissionDialogVisible.value = true
}

// 提交表单
const submitForm = () => {
  roleFormRef.value.validate(valid => {
    if (valid) {
      if (isEdit.value) {
        ElMessage.success('角色编辑成功')
      } else {
        ElMessage.success('角色新增成功')
      }
      dialogVisible.value = false
    }
  })
}

// 提交权限配置
const submitPermission = () => {
  const checkedNodes = treeRef.value.getCheckedNodes(false, true)
  console.log(checkedNodes)
  ElMessage.success('权限配置成功')
  permissionDialogVisible.value = false
}

// 关闭对话框
const handleDialogClose = () => {
  roleFormRef.value.resetFields()
}

// 分页相关
const handleSizeChange = val => {
  pagination.pageSize = val
  ElMessage.success(`每页显示 ${val} 条`)
}

const handleCurrentChange = val => {
  pagination.currentPage = val
  ElMessage.success(`当前页: ${val}`)
}
</script>

<style lang="scss" scoped>
// 使用全局定义的样式

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
